package com.briup.jd2407cms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.briup.jd2407cms.domain.Article;
import com.briup.jd2407cms.domain.Category;
import com.briup.jd2407cms.domain.Comment;
import com.briup.jd2407cms.domain.User;
import com.briup.jd2407cms.domain.extend.ArticleExtend;
import com.briup.jd2407cms.domain.extend.ArticleParam;
import com.briup.jd2407cms.exception.ServiceException;
import com.briup.jd2407cms.mapper.CategoryMapper;
import com.briup.jd2407cms.mapper.CommentMapper;
import com.briup.jd2407cms.mapper.UserMapper;
import com.briup.jd2407cms.result.ResultCode;
import com.briup.jd2407cms.service.ArticleService;
import com.briup.jd2407cms.mapper.ArticleMapper;
import com.briup.jd2407cms.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
* @author 王杰_
* @description 针对表【cms_article】的数据库操作Service实现
* @createDate 2024-11-21 14:43:47
*/
@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper,Article>
    implements ArticleService{
    @Autowired
    ArticleMapper articleMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    CategoryMapper categoryMapper;
    @Autowired
    CommentMapper commentMapper;


    @Override
    public void addOrEdit(Article article, HttpServletRequest request) {
        System.out.println(article);
        Claims claims = JwtUtil.parseJWT(request.getHeader("Authorization"));
        if (article==null){
            throw new ServiceException(ResultCode.USER_IS_NOT_EXIST);
        }
        Integer userId = (Integer) claims.get("userId");
        if (userId!=null&&userMapper.selectById(userId)==null){
            throw new ServiceException(ResultCode.USER_IS_NOT_EXIST);
        }
        article.setUserId(userId.longValue());
        Integer categoryId = article.getCategoryId();
        if (categoryId!=null){
            Category category = categoryMapper.selectById(categoryId);
            if (category==null||category.getParentId()==null){
                throw new ServiceException(ResultCode.CATEGORY_NOT_EXIST);
            }
        }
        Long id = article.getId();
        if (id==null){
            article.setPublishTime(LocalDateTime.now());
            articleMapper.insert(article);
        }else {
            Article oldArticle = articleMapper.selectById(id);
            if (oldArticle==null){
                throw new ServiceException(ResultCode.ARTICLE_NOT_EXIST);
            }
            Integer roleId = (Integer)claims.get("roleId");
            if (roleId==3&&"审核通过".equals(article.getStatus())){
                throw new ServiceException(ResultCode.PARAM_IS_INVALID);
            }
            articleMapper.updateById(article);
        }

    }

    @Override
    public IPage<ArticleExtend> query(ArticleParam articleParam) {
        Page<Article> page = new Page<>(articleParam.getPageNum(), articleParam.getPageSize());
        LambdaQueryWrapper<Article> lqw = new LambdaQueryWrapper<>();
        lqw.eq(articleParam.getUserId()!=null,Article::getUserId,articleParam.getUserId())
                .like(StringUtils.hasText(articleParam.getTitle()),Article::getTitle,articleParam.getTitle())
                .eq(articleParam.getCharged()!=null,Article::getCharged,articleParam.getCharged())
                .eq(articleParam.getCategoryId()!=null,Article::getCategoryId,articleParam.getCategoryId())
                .le(articleParam.getEndTime()!=null,Article::getPublishTime,articleParam.getEndTime())
                .ge(articleParam.getStartTime()!=null,Article::getPublishTime,articleParam.getStartTime())
                .eq(articleParam.getStatus()!=null&& !articleParam.getStatus().isEmpty(),Article::getStatus,articleParam.getStatus());
        Page<Article> articlePage = articleMapper.selectPage(page, lqw);
        List<Article> records = articlePage.getRecords();
        ArrayList<ArticleExtend> articleExtends = new ArrayList<>();
        for (Article art:records){
            Long userId = art.getUserId();
            User user = userMapper.selectById(userId);
            if (user==null){
                continue;
            }
            ArticleExtend articleExtend = new ArticleExtend();
            BeanUtils.copyProperties(art,articleExtend);
            user.setPassword(null);
            articleExtend.setAuthor(user);
            articleExtends.add(articleExtend);
        }
        IPage<ArticleExtend> extendPage = new Page<>();
        extendPage.setRecords(articleExtends);
        extendPage.setTotal(page.getTotal());
        extendPage.setCurrent(page.getCurrent());
        return extendPage;
    }

    @Override
    public void reviewArticle(Long id, String status) {
        if (id==null||status==null){
            throw new ServiceException(ResultCode.PARAM_IS_BLANK);
        }
        if (articleMapper.selectById(id)==null){
            throw new ServiceException(ResultCode.ARTICLE_NOT_EXIST);
        }
        Article article =new Article();
        article.setId(id);
        article.setStatus(status);
        articleMapper.updateById(article);
    }

    @Override
    public ArticleExtend queryById(Long id) {
        if (id==null){
            throw new ServiceException(ResultCode.PARAM_IS_BLANK);
        }

        Article article = articleMapper.selectById(id);
        if (article==null){
            throw new ServiceException(ResultCode.ARTICLE_NOT_EXIST);
        }
        if (!"审核通过".equals(article.getStatus())){
            throw new ServiceException(ResultCode.ARTICLE_NOT_EXIST);
        }
        Long userId = article.getUserId();
        if (userMapper.selectById(userId)==null){
            throw new ServiceException(ResultCode.USER_IS_NOT_EXIST);
        }
        String token = getToken();
        Long currUserId = Long.parseLong(JwtUtil.getUserId(token));
        Integer isVip = userMapper.selectById(currUserId).getIsVip();
        if (!currUserId.equals(article.getUserId())&&article.getCharged()==1&&isVip==0){
            throw new ServiceException(ResultCode.ARTICLE_IS_NOT_VISIBLE);
        }
        ArticleExtend articleExtend = new ArticleExtend();
        BeanUtils.copyProperties(article,articleExtend);
        LambdaQueryWrapper<Comment> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Comment::getArticleId,id).orderByDesc(Comment::getPublishTime).last("limit 3");
        List<Comment> comments = commentMapper.selectList(lqw);
        articleExtend.setComments(comments);
        return articleExtend;


    }

    @Override
    public void deleteByBatch(List<Long> ids) {
        for (Long l:ids){
            articleMapper.deleteById(l);
        }
    }

    private String getToken(){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("Authorization");
        return token;
    }

}




